//
//  SinaStatusListViewModel.swift
//  SinaWeibo
//
//  Created by 王朝阳 on 2016/10/27.
//  Copyright © 2016年 wangzhaoyang. All rights reserved.
//

import UIKit
import SDWebImage

//帮助首页请求数据
class SinaStatusListViewModel: NSObject {
    //定义数组保存微博数据
    var dataArray:[SinaStatusViewModel] = [SinaStatusViewModel]()
    

    //请求首页数据
    func getHomeData(isPullUp:Bool, finish:@escaping (Bool, String)->()) {
        
        //isPullUp = true 代表是上拉加载
        //isPullUp = false 代表是下拉刷新
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        
        if isPullUp {
            maxId = dataArray.last?.statusModel?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
            sinceId = 0
        }else {
            sinceId = dataArray.first?.statusModel?.id ?? 0
            maxId = 0
        }
        let message = "没有加载到最新微博数据"
        HMNetworkTools.sharedTools.homeLoadData(sinceId: sinceId, maxId: maxId, success: { (response) in
            //            print("请求成功",response)
            //判断 response 是否为nil, 是否能转成字典
            guard let resDict = response as? [String: Any] else {
                print("可能为 nil 可能转不出字典")
                finish(false, message)
                return
            }
            //判断字典中的 ststuses 是否为 nil, 是否可以转成数组
            guard let resArr = resDict["statuses"] as? [[String: Any]] else {
                print("可能为 nil 可能转不出数组")
                finish(false, message)
                return
            }
            //使用 YYModel 转成数组
            let statusesArray = NSArray.yy_modelArray(with: SinaStatusModel.self, json: resArr) as! [SinaStatusModel]
            //创建一个临时可变数
            var tempArray:[SinaStatusViewModel] = [SinaStatusViewModel]()
            //遍历
            for model in statusesArray {
                let statusViewModel = SinaStatusViewModel()
                
                statusViewModel.statusModel = model
                //添加viewModel
                tempArray.append(statusViewModel)
                
            }
            //保存数据
            if isPullUp {
                self.dataArray = self.dataArray + tempArray
            }else {
                // 下拉刷新
                self.dataArray = tempArray + self.dataArray
            }
            self.loadSingImage(array: tempArray, finish: finish)
            
        }) { (error) in
            print("请求失败",error)
            finish(false, message)
        }
    }
}
extension SinaStatusListViewModel{
    
    //单张图片下载
    func loadSingImage(array: [SinaStatusViewModel], finish:@escaping (Bool, String)->()){
        
        //1.创建调度组
        let group = DispatchGroup()
        //遍历数组
        for statusViewModel in array {
            //如果是原创微博 && count == 1
            if statusViewModel.statusModel?.pic_urls?.count == 1 {
                let url = URL(string: statusViewModel.statusModel?.pic_urls?.first?.thumbnail_pic ?? "")!
                //加入调度组
                group.enter()
                
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                    print("原创微博下载完成")
                    group.leave()
                })
            }
            //如果是转发微博 && count == 1
            if statusViewModel.statusModel?.retweeted_status?.pic_urls?.count == 1 {
                let url = URL(string: statusViewModel.statusModel?.retweeted_status?.pic_urls?.first?.thumbnail_pic ?? "")!
                //加入调度组
                group.enter()
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                    print("转发微博图片下载完成")
                    group.leave()
                })
            }
        }
        //调度组统一监听单张图片是否下载完成
        group.notify(queue: .main) {
            print("所有图片全部下载完成")
            var message = "没有加载到最新微博数据"
            if array.count > 0 {
                message = "加载了\(array.count)条微博"
            }
            finish(true, message)
        }
    }
}
